/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.app.param.ScoreImportParam;
import com.yami.shop.bean.param.UserScoreRecordImportParam;
import com.yami.shop.bean.model.UserScoreRecord;
import com.yami.shop.service.UserScoreRecordService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author lgh on 2018/10/16.
 */
@Api(tags = "用户积分接口")
@RestController
@RequestMapping("/admin/score")
public class UserScoreController {
    @Autowired
    private UserScoreRecordService userScoreRecordService;
    @Autowired
    private UserService userService;

    /**
     * 导入积分
     * @return
     */
    @PostMapping("/import")
    @ApiOperation(value = "导入积分记录", notes = "导入积分记录")
    public ResponseEntity importScore(@RequestBody ScoreImportParam[] scoreImportParams){
        for (ScoreImportParam param : scoreImportParams) {
            userService.addScore(param.getUserCode(),param.getScore(),"积分导入");
        }
        return ResponseEntity.ok().build();
    }


    /**
     * 添加记录
     */
    @PutMapping
    @Transactional
    @ApiOperation(value = "添加积分记录", notes = "添加积分记录")
    public ResponseEntity<Void> put(@RequestBody UserScoreRecordImportParam scoreRecordParam) {
        Integer type = scoreRecordParam.getType();
        String userId = scoreRecordParam.getUserId();
        double amount = scoreRecordParam.getAmount();
        //修改用户积分
        if(type == 1){
            userService.subScoreByUid(userId,amount,"后台扣除");
        }else{
            userService.addScoreByUid(userId,amount,"后台发放");
        }

        return ResponseEntity.ok().build();
    }

    /**
     * 查询记录
     */
    @GetMapping
    @ApiOperation(value = "查询积分记录", notes = "查询积分记录")
    public ResponseEntity get(@ApiParam(value = "用户id", required = true) String userId,
                              @ApiParam(value = "记录类型 1支出 2收入") Integer type) {
        LambdaQueryWrapper<UserScoreRecord> query = Wrappers.lambdaQuery(new UserScoreRecord())
                .eq(UserScoreRecord::getUid, userId)
                .eq(type!=null,UserScoreRecord::getType, type);
        List<UserScoreRecord> list = userScoreRecordService.list(query);

        return ResponseEntity.ok(list);
    }
}
